//
//  FieldObservationEditViewController.m
//  Tazama NGO
//
//  Created by jsheriff on 3/11/11.
//  Copyright 2011 The MITRE Corporation. All rights reserved.
//

#import "FieldObservationEditViewController.h"
#import "GeoRefCustomCell.h"

#define kGeneralSection 0
#define kObservationTextSection 1
#define kGeorefSection 2
#define kImageSection 3

#define kImmediateNeedsField 0
#define kConfidenceField 1
#define kSeverityField 2
#define kObservationTextField 3
#define kGeorefField 4
#define kImageField 5

@implementation FieldObservationEditViewController

@synthesize delegate;
@synthesize fieldObservation;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelPressed:)];
	self.navigationItem.leftBarButtonItem = cancelButton;
	[cancelButton release];

    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(donePressed:)];
	self.navigationItem.rightBarButtonItem = doneButton;
	[doneButton release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        return YES;
    }
    else {
        return UIInterfaceOrientationIsPortrait(interfaceOrientation);
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 4;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == kGeneralSection)
		return 3;
	else if (section == kObservationTextSection)
		return 1;
	else if (section == kGeorefSection)
		return 1;
    else if (section == kImageSection)
        return 1;
	else
		return 0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *title = @"";
	
	if (section == kObservationTextSection)
		title = @"Observation";
	else if (section == kGeorefSection)
		title = @"Georef";
	
	return title;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	if (indexPath.section == kImageSection && fieldObservation.image != nil)
        return 120;
    else
        return 46;
}

-(UITableViewCell *)getCell:(UITableView *)tableView
{
	static NSString *cellIdentifier = @"FieldObservationGeneralCell";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	if (cell == nil)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:cellIdentifier] autorelease];
	}	
	
	cell.detailTextLabel.font = [UIFont boldSystemFontOfSize:18];
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	
	return cell;
}

-(UITableViewCell *)getCellObservationText:(UITableView *)tableView
{
	static NSString *cellIdentifier = @"FieldObservationObservationTextCell";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	if (cell == nil)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier] autorelease];
	}	
	
	cell.textLabel.font = [UIFont systemFontOfSize:16];
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	
	return cell;
}

-(GeoRefCustomCell *)getCellGeoref:(UITableView *)tableView
{
	static NSString *cellIdentifier = @"FieldObservationGeorefCell";
	
	GeoRefCustomCell *cell = (GeoRefCustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	if (cell == nil)
	{
		cell = [[[GeoRefCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier mapButton:NO] autorelease];
	}
	
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
	return cell;
}

-(UITableViewCell *)getCellDataMissing:(UITableView *)tableView
{
	static NSString *cellIdentifier = @"FieldObservationCellDataMissing";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	if (cell == nil)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
	}	
	
	cell.textLabel.font = [UIFont boldSystemFontOfSize:16];
	cell.textLabel.textColor = [UIColor blueColor];
	cell.textLabel.textAlignment = UITextAlignmentCenter;

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

	return cell;
}

-(UITableViewCell *)getCellImage:(UITableView *)tableView
{
	static NSString *cellIdentifier = @"EventDetailCellImage";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	if (cell == nil)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier] autorelease];
	}	
	
	cell.textLabel.font = [UIFont systemFontOfSize:16];
	
	return cell;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	NSUInteger row = [indexPath row];
	NSUInteger section = [indexPath section];
	
	UITableViewCell *cell;
	
	if (section == kGeneralSection)
	{
		if (row == 0) {
            if (fieldObservation.immediateNeeds.length == 0) { 
                cell = [self getCellDataMissing:tableView];
                cell.textLabel.text = @"set immediate needs";
            }
            else {
                cell = [self getCell:tableView];
                cell.textLabel.text = @"Needs";
                cell.detailTextLabel.text = fieldObservation.immediateNeeds;
            }
		}
		else if (row == 1) {
            if (fieldObservation.confidence.length == 0) {
                cell = [self getCellDataMissing:tableView];
                cell.textLabel.text = @"set confidence";
            }
            else {
                cell = [self getCell:tableView];
                cell.textLabel.text = @"Confidence";
                cell.detailTextLabel.text = [fieldObservation.confidence capitalizedString];
            }
		}
		else if (row == 2) {
            if (fieldObservation.severity.length == 0) {
                cell = [self getCellDataMissing:tableView];
                cell.textLabel.text = @"set severity";
            }
            else {
                cell = [self getCell:tableView];
                cell.textLabel.text = @"Severity";
                cell.detailTextLabel.text = [fieldObservation.severity capitalizedString];
            }
		}
	}
	else if (section == kObservationTextSection)
	{
        if (fieldObservation.observationText.length == 0) {
            cell = [self getCellDataMissing:tableView];
            cell.textLabel.text = @"add observation text";
        }
        else {
            cell = [self getCellObservationText:tableView];
            cell.textLabel.text = fieldObservation.observationText;
        }
	}
	else if (section == kGeorefSection)
	{
		GeoRefCustomCell *geoRefCell = [self getCellGeoref:tableView];
		//  \xC2\xB0 is a degree symbol
		geoRefCell.latitudeLabel.text = [NSString stringWithFormat:@"Lat %2.4f\xC2\xB0", fieldObservation.location.latitude];		
		geoRefCell.longitudeLabel.text = [NSString stringWithFormat:@"Lon %3.4f\xC2\xB0", fieldObservation.location.longitude];	
		cell = geoRefCell;
	}
    else if (section == kImageSection)
	{
		if (fieldObservation.image != nil)
		{
			cell = [self getCellImage:tableView];
            
            if (fieldObservation.image != nil) {
                UIGraphicsBeginImageContext( CGSizeMake(108, 108) );
                [fieldObservation.image drawInRect:CGRectMake( 0, 0, 108, 108)];
                UIImage *thumbnail = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();
                cell.imageView.image = thumbnail;
                //            [thumbnail release];
            }
		}
		else
		{
			cell = [self getCellDataMissing:tableView];
			cell.textLabel.text = @"add image";
			cell.detailTextLabel.text = @"";
			cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		}
	}
    
	return cell;
}

-(IBAction)cancelPressed:(id)sender {
    if ([delegate respondsToSelector:@selector(didCancelFieldObservationEdit)])
	{
		[delegate didCancelFieldObservationEdit];
	}
}

-(IBAction)donePressed:(id)sender {
    if ([delegate respondsToSelector:@selector(didSaveFieldObservationEdit)])
	{
		[delegate didSaveFieldObservationEdit];
	}
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	NSUInteger row = [indexPath row];
	NSUInteger section = [indexPath section];
	
	if (section == kGeneralSection)
	{
		if (row == 0) {
            textEditController = [[TextEditController alloc] initWithNibName:@"TextEditController" bundle:nil];
            textEditController.delegate = self;
            textEditController.title = @"Immediate Needs";
            textEditController.text = fieldObservation.immediateNeeds;
            fieldModified = kImmediateNeedsField;
            [self.navigationController pushViewController:textEditController animated:YES];
        }
		else if (row == 1) {
            menuTableViewController = [[MenuTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
            menuTableViewController.delegate = self;
            menuTableViewController.title = @"Confidence";
            menuTableViewController.selectedMenuItem = fieldObservation.confidence;
            menuTableViewController.menuItemList = [NSArray arrayWithObjects:@"Observed", @"Likely", @"Possible", @"Unlikely", @"Unknown", nil];
            fieldModified = kConfidenceField;
            [self.navigationController pushViewController:menuTableViewController animated:YES];
        }
		else if (row == 2) {
            menuTableViewController = [[MenuTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
            menuTableViewController.delegate = self;
            menuTableViewController.title = @"Severity";
            menuTableViewController.selectedMenuItem = fieldObservation.severity;
            menuTableViewController.menuItemList = [NSArray arrayWithObjects:@"Immediate", @"Expected", @"Future", @"Passed", @"Unknown", nil];
            fieldModified = kSeverityField;
            [self.navigationController pushViewController:menuTableViewController animated:YES];
        }
    }
	else if (section == kObservationTextSection && indexPath.row == 0) {
		textEditViewController = [[TextEditViewController alloc] initWithNibName:@"TextEditViewController" bundle:nil];
        textEditViewController.delegate = self;
		textEditViewController.title = @"Obsrvn Text";
		textEditViewController.text = fieldObservation.observationText;
        fieldModified = kObservationTextField;
		[self.navigationController pushViewController:textEditViewController animated:YES];
	}
	else if (section == kGeorefSection && indexPath.row == 0) {
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            latLongSelectionController_iPad = [[LatLongSelectionController_iPad alloc] initWithNibName:@"LatLongSelectionController_iPad" bundle:nil];
            latLongSelectionController_iPad.delegate = self;
            latLongSelectionController_iPad.title = @"Georef";
            latLongSelectionController_iPad.location = fieldObservation.location;
            fieldModified = kGeorefField;
            [self.navigationController pushViewController:latLongSelectionController_iPad animated:YES];
        }
        else {
            latLongSelectionController = [[LatLongSelectionController alloc] initWithNibName:@"LatLongSelectionController" bundle:nil];
            latLongSelectionController.delegate = self;
            latLongSelectionController.title = @"Georef";
            latLongSelectionController.location = fieldObservation.location;
            fieldModified = kGeorefField;
            [self.navigationController pushViewController:latLongSelectionController animated:YES];
        }
	}
    else if (section == kImageSection && indexPath.row == 0) {
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            if (imageSelectionController_iPad == nil)
            {
                imageSelectionController_iPad = [[ImageSelectionController_iPad alloc] initWithNibName:@"ImageSelectionController_iPad" bundle:nil];
            }
            imageSelectionController_iPad.title = @"Image";
            imageSelectionController_iPad.imageView.image = fieldObservation.image;
            imageSelectionController_iPad.delegate = self;
            UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imageSelectionController_iPad];
            fieldModified = kImageField;
            [self presentModalViewController:navigationController animated:YES];
        }
        else {
            if (imageSelectionController == nil)
            {
                imageSelectionController = [[ImageSelectionController alloc] initWithNibName:@"ImageSelectionController" bundle:nil];
            }
            imageSelectionController.title = @"Image";
            imageSelectionController.imageView.image = fieldObservation.image;
            imageSelectionController.delegate = self;
            fieldModified = kImageField;
            [self.navigationController pushViewController:imageSelectionController animated:YES];
        }
	}
}

-(void)didSaveItem {
    if (fieldModified == kImmediateNeedsField) {
        fieldObservation.immediateNeeds = textEditController.text;
        [textEditController release];
        textEditController = nil;
        [self.navigationController popViewControllerAnimated:YES];
        [self.tableView reloadData];	
    }
    else if (fieldModified == kObservationTextField) {
        fieldObservation.observationText = textEditViewController.text;
        [textEditViewController release];
        textEditViewController = nil;
        [self.navigationController popViewControllerAnimated:YES];
        [self.tableView reloadData];	
    }
    else if (fieldModified == kGeorefField) {
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            fieldObservation.location = latLongSelectionController_iPad.location;
            [latLongSelectionController_iPad release];
            latLongSelectionController_iPad = nil;
            [self.navigationController popViewControllerAnimated:YES];
            [self.tableView reloadData];	
        }
        else {
            fieldObservation.location = latLongSelectionController.location;
            [latLongSelectionController release];
            latLongSelectionController = nil;
            [self.navigationController popViewControllerAnimated:YES];
            [self.tableView reloadData];	
        }
    }
    else if (fieldModified == kImageField)
	{
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            NSLog(@"%f/%f", imageSelectionController_iPad.imageView.image.size.width, imageSelectionController.imageView.image.size.height);
            fieldObservation.image = imageSelectionController_iPad.imageView.image;
//            fieldObservation.image = [UIImage imageWithCGImage:[imageSelectionController_iPad.imageView.image CGImage] scale:2.0 orientation:UIImageOrientationUp];
            NSLog(@"original size = %f, %f  new size = %f, %f", imageSelectionController_iPad.imageView.image.size.width, imageSelectionController_iPad.imageView.image.size.height, fieldObservation.image.size.width, fieldObservation.image.size.height);
            [self dismissModalViewControllerAnimated:YES];
            [self.tableView reloadData];
        }
        else {
            // Make the image half the original size
            NSLog(@"%f/%f", imageSelectionController.imageView.image.size.width, imageSelectionController.imageView.image.size.height);
            fieldObservation.image = [UIImage imageWithCGImage:[imageSelectionController.imageView.image CGImage] scale:2.0 orientation:UIImageOrientationUp];
            NSLog(@"original size = %f, %f  new size = %f, %f", imageSelectionController.imageView.image.size.width, imageSelectionController.imageView.image.size.height, fieldObservation.image.size.width, fieldObservation.image.size.height);
            //        [imageSelectionController release];
            //        imageSelectionController = nil;
            [self.navigationController popViewControllerAnimated:YES];
            [self.tableView reloadData];	
            
        }	
	}
}

-(void)didChooseMenuItem {
    if (fieldModified == kConfidenceField) {
        fieldObservation.confidence = menuTableViewController.selectedMenuItem;
        [menuTableViewController release];
        menuTableViewController = nil;
        [self.navigationController popViewControllerAnimated:YES];
        [self.tableView reloadData];	
    }
    else if (fieldModified == kSeverityField) {
        fieldObservation.severity = menuTableViewController.selectedMenuItem;
        [menuTableViewController release];
        menuTableViewController = nil;
        [self.navigationController popViewControllerAnimated:YES];
        [self.tableView reloadData];	
    }
}

-(void)didCancelMenuItem {
    [menuTableViewController release];
    menuTableViewController = nil;
    [self.navigationController popViewControllerAnimated:YES];
}

@end
